package IO;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-11-02
 * Time: 18:22
 */
//查找指定目录下包含关键字的文件
public class FileSearchAdv {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查找的目录的绝对路径");
        String path = scanner.next();
        System.out.println("请输入关键词");
        String key = scanner.next();

        //判断是否为目录
        File dir = new File(path);
        if(!dir.isDirectory()){
            System.out.println("路径错误或为文件");
        }

        //目录下查找
        search(dir,key);
    }

    public static void search(File dir,String key) throws IOException {
        //获取目录下的所有文件对象
        File[] files = dir.listFiles();
        if(files == null) return;

        //遍历查找
        for (int i = 0; i < files.length; i++) {
            //判断是否为文件
            if(files[i].isFile()){
                check(files[i],key);
            }else{//为目录
                search(files[i],key);
            }
        }
    }

    public static void check(File file,String key) throws IOException {
        if(file.getName().contains(key)){
            System.out.println("查找到文件 " + file.getName() + " 包含关键字,所在路径为：" + file.getCanonicalFile());
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();

        //创建字符输入流对象
        try(Reader reader = new FileReader(file);){
            //读取文件
            while(true){
                char[] ch = new char[1024];
                int n = reader.read(ch);
                if(n == -1){
                    break;
                }
                stringBuilder.append(ch,0,n);
            }
        }

        if(stringBuilder .indexOf(key) >= 0){
            System.out.println("查找到文件内容在 " + file.getName() + " 包含关键字,所在路径为：" + file.getCanonicalFile());
        }
    }
}
